<template>
    <el-dialog
        v-model="showflag"
        :title="title"
        width="50vw"
        align-center
        :close-on-click-modal="false"
        @close="resetdata">
        <div style="padding: 0 40px">
            <el-form
                ref="ruleFormRef"
                style="width: 100%"
                :model="ruleForm"
                :rules="rules"
                label-width="auto"
                class="demo-ruleForm"
                :size="formSize"
                status-icon>
                <div class="linebox">
                    <!-- <el-form-item label="订单编号" prop="orderCode">
                        <el-input
                            v-model="ruleForm.orderCode" style="width: 70%"
                            :disabled="!isedit"
                            placeholder="请输入订单编号" />
                    </el-form-item> -->
                    <el-form-item label="利用单位" prop="operate_id">
                        <el-select style="width: 70%"
                            @change="changeoperate"
                            v-model="ruleForm.operate_id"
                            placeholder="请选择"
                            filterable
                            :disabled="!isedit">
                            <el-option
                                v-for="(item, index) in operatelist"
                                :key="index"
                                :label="item.name"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="所属省份" prop="province">
                        <el-select style="width: 70%"
                            @change="changprovince"
                            v-model="ruleForm.province"
                            placeholder="请选择"
                            :disabled="!isedit">
                            <el-option
                                v-for="(item, index) in provincelist"
                                :key="index"
                                :label="item.name"
                                :value="item.name" />
                        </el-select>
                    </el-form-item>
                </div>
                
                <div class="linebox">                    
                    <el-form-item label="所属市" prop="city">
                        <el-select style="width: 70%"
                            @change="changcity"
                            v-model="ruleForm.city"
                            placeholder="请选择"
                            :disabled="!isedit">
                            <el-option
                                v-for="(item, index) in citylist"
                                :key="index"
                                :label="item.name"
                                :value="item.name" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="所属区县" prop="area">
                        <el-select style="width: 70%"
                            v-model="ruleForm.area"
                            placeholder="请选择"
                            :disabled="!isedit">
                            <el-option
                                v-for="(item, index) in arealist"
                                :key="index"
                                :label="item.name"
                                :value="item.name" />
                        </el-select>
                    </el-form-item>
                </div>

                <div class="linebox">
                    <el-form-item label="联系人" prop="uname">
                        <el-input
                            v-model="ruleForm.uname" style="width: 70%"
                            :disabled="!isedit"
                            placeholder="请输入联系人" />
                    </el-form-item>
                    <el-form-item label="联系电话" prop="telphone">
                        <el-input
                            v-model="ruleForm.telphone" style="width: 70%"
                            :disabled="!isedit"
                            placeholder="请输入联系电话" />
                    </el-form-item>
                </div>

                <div class="linebox">                    
                    
                    <el-form-item label="详细地址" prop="address">
                        <el-input style="width: 70%"
                            v-model="ruleForm.address"
                            :disabled="!isedit"
                            placeholder="请输入详细地址" />
                    </el-form-item>
                </div>


                <div style="width:100%;padding:10px;background:#f5f5f5;margin-bottom:30px">
                    <div class="headerlist" :class="isedit?'':'box33'">
                        <div>所属分类</div>
                        <div>分类单价</div>
                        <div>商品重量(kg)</div>
                        <div v-if="isedit">操作</div>
                    </div>
                    <div style="margin-top:10px;">
                        <div class="listbox" :class="isedit?'':'box33'" v-for="(item, index) in ruleForm.list" :key="index">
                            <div>
                                <el-select style="width: 70%"
                                    @change="()=>changeproduct(index)"
                                    v-model="item.product_name"
                                    placeholder="请选择"
                                    filterable
                                    :disabled="!isedit">
                                    <el-option
                                        v-for="(item, index) in productlist"
                                        :key="index"
                                        :label="item.materialName"
                                        :value="item.materialName" />
                                </el-select>
                            </div>
                            <div>
                                <el-input style="width: 70%"
                                    v-model="item.product_price"
                                    type="number"
                                    :disabled="!isedit"
                                    placeholder="请输入分类单价" />
                            </div>
                            <div>
                                <el-input style="width: 70%"
                                    v-model="item.product_num"
                                    type="number"
                                    :disabled="!isedit"
                                    placeholder="请输入商品重量(kg)" />
                            </div>
                            <div v-if="isedit">
                                <el-button type="danger" size="small" @click="delline(index)">删除</el-button>
                            </div>
                        </div>
                    </div>
                    <div style="padding-left:0.32rem;" v-if="isedit">
                        <el-button type="success" size="small" @click="addline">添加</el-button>
                    </div>
                    
                </div>
               
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="showflag = false">取消</el-button>
                <el-button
                    v-if="isedit"
                    type="primary"
                    @click="submitForm(ruleFormRef)">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, ref, provide, reactive, toRaw, inject } from "vue";
import { ElMessage } from "element-plus";
import { post, baseURL } from "../../../../api/request";
import type { FormInstance, FormRules } from "element-plus";

let showflag = ref(false);
let title = ref("新增转出");
let isedit = ref(true);
let device_id = ref("");
let token = ref("");
const getdata = inject<() => void>("getdata")!; //父组件的方法
let citylist = ref([]);
let arealist = ref([]);
let provincelist = ref([]);

onMounted(() => {
    token.value = localStorage.getItem("token") || "";

    post({
        url: "/api/area/index",
        data: {
            parent_id: '',
        },
    }).then((res: any) => {
        provincelist.value = res.data.list;
    });


    post({
        url: "/api/area/index",
        data: {
            parent_id: 3021,
        },
    }).then((res: any) => {
        citylist.value = res.data.list;
    });
});

const changprovince = (e: any) => {
    let id = provincelist.value.find((item: any) => item.name == e)?.id;
    post({
        url: "/api/area/index",
        data: {
            parent_id: id,
        },
    }).then((res: any) => {
        citylist.value = res.data.list;
        arealist.value = [];
        ruleForm.area = ''
        ruleForm.city = ''
    });
};

const changcity = (e: any) => {
    let id = citylist.value.find((item: any) => item.name == e)?.id;
    post({
        url: "/api/area/index",
        data: {
            parent_id: id,
        },
    }).then((res: any) => {
        arealist.value = res.data.list;
        ruleForm.area = ''
    });
};

const changeoperate = (e: any) => {
    let item = operatelist.value.find((item: any) => item.id == e);
    if(item){
        ruleForm.city = item.city;
        ruleForm.area = item.area;
        ruleForm.province = item.province;
        ruleForm.address = item.address;
        ruleForm.uname = item.uname;
        ruleForm.telphone = item.telphone;
        getarelist()
    }
};
//根据所属市区和区县的名字 去查找他们的parent_id 获取下级区县的列表数据
const getarelist = ()=>{
    let province_id = provincelist.value.find((item: any) => item.name == ruleForm.province)?.id;
        post({
            url: "/api/area/index",
            data: {
                parent_id: province_id,
            },
        }).then((res: any) => {
            citylist.value = res.data.list;
            let city_id = citylist.value.find((item: any) => item.name == ruleForm.city)?.id;
            post({
                url: "/api/area/index",
                data: {
                    parent_id: city_id,
                },
            }).then((res: any) => {
                arealist.value = res.data.list;
            });
        });
}

//选择分类回填价格
const changeproduct = (index: number) => {
    let item = productlist.value.find((item: any) => item.materialName == ruleForm.list[index].product_name);
    if(item){
        ruleForm.list[index].product_price = item.price;
    }
};


//利用单位和所属分类
let operatelist = ref([]);
let productlist = ref([]);

post({
    url: "/api/operate/index",
    data: {
        page: 1,
        size: 10000,
    },
}).then((res: any) => {
    operatelist.value = res.data.list;
});

post({
    url: "/api/types/index",
    data: {
        page: 1,
        size: 10000,
    },
}).then((res: any) => {
    productlist.value = res.data;
});


const delline = (index: number) => {
    ruleForm.list.splice(index, 1);
};

const addline = () => {
    ruleForm.list.push({
        product_name:'',
        product_price:0,
        product_num:0,
        product_money:0
    })
};


//表单相关---------------------------------------
interface RuleForm {
    id: string;
    name: string;
    address:string;
    province:string;
    city: string;
    area: string;
    uname: string;
    telphone: string;
    operate_id: string;    
    list:any[
        {
            product_name: string;
            product_price:number;
            product_num:number
        }
    ];
    
}

const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
let ruleForm = reactive<RuleForm>({
    id: "",
    address: "",
    province: "青海省",
    city: "",
    area: "",
    uname: "",
    telphone: "",
    operate_id: "",
    list:[
        {
            product_name:'',
            product_price:0,
            product_num:0
        }
    ]
});

const rules = reactive<FormRules<RuleForm>>({
    // orderCode: [{ required: true, message: "请填写订单编号", trigger: "blur" }],
    address: [{ required: true, message: "请填写详细地址", trigger: "blur" }],
    province: [{ required: true, message: "请选择所属省", trigger: "blur" }],
    city: [{ required: true, message: "请选择所属市", trigger: "blur" }],
    area: [{ required: true, message: "请选择所属区县", trigger: "blur" }],
    uname: [{ required: true, message: "请填写联系人", trigger: "blur" }],  
    telphone: [{ required: true, message: "请填写联系电话", trigger: "blur" }],
    operate_id: [{ required: true, message: "请选择所属单位", trigger: "blur" }]
});

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;

    //判断ruleForm中的list的长度必须大于0
    if(ruleForm.list.length == 0){
        ElMessage.error("请添加转出商品!");
        return;
    }

    //判断ruleForm中的list是否有数据没有选择分类
    let flag = ruleForm.list.some((item: any) => item.product_name == '');
    if(flag){
        ElMessage.error("请选择分类!");
        return;
    }
    



    await formEl.validate((valid, fields) => {
        if (valid) {
            post({
                url: ruleForm.id
                    ? "/api/orderchu/details"
                    : "/api/orderchu/add",
                data: toRaw(ruleForm),
            }).then((res: any) => {
                ElMessage.success("操作成功!");
                getdata();
                showflag.value = false;
                resetdata();
            });
        } else {
            console.log("error submit!");
        }
    });
};
//表单END---------------------------------------



const resetdata = () => {
    Object.assign(ruleForm, {
        id: "",
        address: "",
        province: "青海省",
        city: "",
        area: "",
        uname: "",
        telphone: "",
        operate_id: "",
        list:[
            {
                product_name:'',
                product_price:0,
                product_num:0
            }
        ]
    });
    isedit.value = true;
    title.value = "新增转出";
};

// 通过 defineExpose 暴露给父组件
defineExpose({
    showflag,
    title,
    isedit,
    device_id,
    ruleForm,
    getarelist
});
</script>

<style lang="scss" scoped>
:deep(.el-form-item) {
    margin-bottom: 30px;
    width: 50%;
}
.linebox {
    display: flex;
    align-items: flex-start;
    width: 100%;
}
:deep(.avatar-uploader .avatar) {
    width: 178px;
    height: 178px;
    display: block;
}
:deep(.avatar-uploader .el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

:deep(.avatar-uploader .el-upload:hover) {
    border-color: var(--el-color-primary);
}

:deep(.el-icon.avatar-uploader-icon) {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
.headerlist{
    display:flex;
    align-center:center;
    div{
        width:25%;
        text-align:center;
    }
}
.listbox{
    display:flex;
    align-center:center;
    margin-bottom:15px;
    div{
        width:25%;
        text-align:center;
    }
}
.box33 div{
    width:33%;
}
</style>
